<template>
	<!-- 登录界面，点击按钮微信授权登录 -->
	<view class="page">
		<!-- #ifdef APP-PLUS -->
		<view class="Image">
			<image src="../../static/logo.png" mode=""></image>
		</view>
		<view>
			<!-- <button class="login_button" type="primary" @click="getUserInfo" withCredentials="true" lang="zh_CN">一键登录</button> -->
			<button class="login_button" type="primary" @click="appLogin()" withCredentials="true"
				lang="zh_CN">微信授权登录</button>
			<!-- <button class="login_button" type="primary" @click="appLogin()">微信授权登录</button> -->
			<!-- <button class="login_button" type="default" @click="appleLogin()">Sign in with Apple</button> -->
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<view>
			<view class="Image">
				<image src="cloud://inspace-v1.696e-inspace-v1-1302892928/institutionImage/logo.png" mode=""></image>
			</view>
			<view class="content">
				<view style="font-size: 30rpx;">
					申请获取一下权限
				</view>
				<text style="font-size: 30rpx;">-获得你的公开信息（昵称，头像，地区等)</text>
			</view><button class="login_button" type="primary" @click="getUserInfo()" withCredentials="true"
				lang="zh_CN">一键登录</button>

		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import cloudbase from '@cloudbase/js-sdk';

	const db = cloudbase.database();
	let weixinAuthService;
	export default {
		data() {
			return {
				title: '登录中',
				code: '',
				// session_key: '',
				userInfo: {
					nickName: '',
					openId: '',
					avatarUrl: '',
					gender: '',
					country: '',
					province: '',
					city: ''
				},
				newUserInfo: '',
				from: '',
				hasWeixinAuth: false
			}
		},
		onLoad(e) {
			if (e.from) this.from = e.from;
			// #ifdef APP-PLUS
			plus.oauth.getServices((services) => {
				weixinAuthService = services.find((service) => {
					return service.id === 'weixin'
				})
				if (weixinAuthService) {
					this.hasWeixinAuth = true
				}
			});
			// #endif
		},
		methods: {
			// 微信小程序登录
			getUserInfo: function(res) {
				// #ifdef MP-WEIXIN
				let that = this;
				uni.getUserProfile({
					desc: '用于完善会员资料',
					lang: 'zh_CN',
					success: (result) => {
						that.newUserInfo = result.userInfo;
						uni.getProvider({
							service: 'oauth',
							success: function(res) {
								if (~res.provider.indexOf('weixin')) {
									// 使用通用的方法登录
									that.getWeixinCode().then(res => {
										uni.showLoading({
											title: '登录中……',
											mask: true
										})
										that.code = res.code;
										that.getOpenId(res);
									}).catch(err => {
										console.log("登录失败");
										console.log(err);
									});
								}
							}
						})
					}
				})
				//#endif
			},
			// 苹果登录
			appleLogin: function() {
				uni.login({
					provider: 'apple',
					success: function(loginRes) {
						// 登录成功  
						uni.getUserInfo({
							provider: 'apple',
							success(res) {
								// 获取用户信息成功  
								console.log(res)
								/*
								    返回的数据
								    {
								        "errMsg": "getUserInfo:ok",
								        "rawData": "json字符串",
								        "userInfo": {
								            "openId": "xxx.xxxxx.xxx", // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
								            "fullName": {}, // 当且仅当第一次授权才会返回
								            "authorizationCode": "12345678xxx", // 服务器验证需要使用的参数
								            "identityToken": "header.payload.signature", // 服务器验证需要使用的参数
								            "realUserStatus": 1 // 用于判断当前登录的苹果账号是否是一个真实用户
								        },
								        "signature": ""
								    }
								*/
								if (res.userInfo.openId != undefined) {
									uni.showToast({
										title: '登录成功',
										icon: 'none'
									})
								}
							}
						})
					},
					fail: function(err) {
						console.log(err)
					}
				});
			},
			// app微信登录
			appLogin: function(res) {
				// #ifdef APP-PLUS
				var that = this;
				uni.showLoading({
					title: '登录中…',
					mask: true
				})
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						console.info(JSON.stringify(res));
						//支持微信、qq和微博等
						if (~res.provider.indexOf('weixin')) {
							console.log('微信登录');
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									console.info('-------获取openid(unionid)-----');
									console.info(JSON.stringify(loginRes));
									let openId = loginRes.authResult.openid;
									
									// 获取用户信息
									uni.getUserInfo({
										provider: 'weixin',
										success: function(infoRes) {
											console.log('-------获取微信用户所有-----');
											console.log(JSON.stringify(infoRes.userInfo));
											that.newUserInfo = infoRes.userInfo;
										}
									});
									
									// 获取用户登录信息
									that.userInfo.openId = openId;
									getApp().globalData.userInfo.openId = openId;
									that.getUser(openId);
								},
								fail: function() {
									console.log('fail');
								},
								complete: function() {
									uni.hideLoading();
								}
							});
						} else {
							console.log('登录失败')
						}
					}
				});
				// #endif
			},
			// app 获取code
			getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code);
						},
						fail(err) {
							reject(new Error('微信登录失败'));
						}
					})
					// #endif
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code);
					}, function(err) {
						reject(new Error('微信登录失败'));
					});
					// #endif
				})
			},
			// app 通过code获取openid
			

			// 获取用户的openId
			getOpenId: function(code) {
				cloudbase.callFunction({
					name: "getOpenId",
					data: {
						code: code
					}
				}).then(res => {
					console.log(res.result.openid);
					this.userInfo.openId = res.result.openid;
					getApp().globalData.userInfo.openId = res.result.openid;
					getApp().globalData.userInfo.session_key = res.result.session_key;
					this.getUser(this.userInfo.openId);
					// console.log(this.userInfo.openId);
				}).catch(error => {
					console.log(error)
				})

			},
			// 获取数据库里用户的信息
			getUser: function(openId) {
				cloudbase.callFunction({
					name: "getUserInfo",
					data: {
						openId: openId
					}
				}).then(res => {
					// console.log(res);
					let that = this;
					let list = res.result.data;
					if (list.length != 0) {
						Object.assign(getApp().globalData.userInfo, list[0]);
						// 设置底部导航栏
						if (list[0].type == '机构') {
							// 获取对应的机构的授权状态
							db.collection('institution').where({
								_id: list[0].institutionId
							}).field({
								auth: true
							}).get().then(res => {
								console.log('机构登录');
								console.log('授权状态 => ' + list[0].auth);
								if (list[0].auth) {
									uni.navigateBack({
										delta: 1
									})
									uni.setTabBarItem({
										index: 0,
										text: '运营'
									}).then(res => {
										uni.setTabBarItem({
											index: 1,
											text: '管理',
										}).then(res => {
											uni.setTabBarItem({
												index: 2,
												text: '教研',
											})
										})
									})
								} else {
									getApp().globalData.userInfo.openId = '';
									getApp().globalData.userInfo.type = '学生';
									uni.navigateTo({
										url: '../submitSuccess/submitSuccess?index=4'
									})
								}
							})
						} else {
							console.log(this.from);
							if (this.from == 'register') {
								console.log('返回个人页面');
								uni.switchTab({
									url: '../mine/mine'
								})
							} else {
								uni.navigateBack({
									delta: 1
								})
							}
						}
					} else {
						// 获取新的用户信息
						Object.assign(getApp().globalData.userInfo, that.newUserInfo)
						if (!getApp().globalData.userInfo.isRegister) {
							uni.redirectTo({
								url: "../choose/choose",
							})
							uni.hideHomeButton();
						} else {
							console.log(this.from);
							if (this.from == 'register') {
								uni.navigateTo({
									url: '../mine/mine'
								})
							} else {
								uni.navigateBack({
									delta: 1
								})
							}

						}
					}
					uni.hideLoading();
				}).catch(error => {
					console.log(error)
				})

			},

			getSetting: function() {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success(res) {
							if (res.authSetting['scope.userInfo']) {
								console.log('存在');
								resolve(true);
							} else {
								resolve(false);
							}
						}
					})
				})
			}
		}
	}
</script>

<style>
	.page {
		width: 750rpx;
		height: 1435rpx;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
	}

	.Image {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
	}

	.Image image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		margin-top: 40rpx;
	}

	.login_button {
		margin-top: 4vh;
		border-radius: 80rpx;
		width: 80vw;
		font-size: 35rpx;
		margin-left: auto;
		margin-right: auto;
	}
</style>
